# XPath Extensions

import amplitude
from lxml import etree
from copy import deepcopy
from amplitude.dict import Dict
    
def upper(c, arg):
    "uppercase a string or element or sequence of elements"
    print type(arg)
    if type(arg) in [unicode, str]: return arg.upper()
    else:
        if type(arg)==etree._Element:
            arg.text = arg.text.upper()
            print arg.text
        for a in arg:
            a = upper(c, a)
            if type(arg)==etree._Element:
                a.tail = (a.tail or '').upper()
                print a.tail
        return arg

def lower(c, arg):
    "lowercase a string or element or sequence of elements"
    if type(arg) in [unicode, str]: return arg.lower()
    else:
        if type(arg)==list:
            for a in arg:
                lower(c, a)
                a.tail = (a.tail or '').lower()
                print a.tail
        elif type(arg)==etree._Element:
            arg.text = arg.text.lower()
            print arg.text
            lower(c, arg.getchildren())
        return arg

# == Register XPath Extension Functions: Use amplitude.NAMESPACE == 
ampns = etree.FunctionNamespace(amplitude.NAMESPACE['url'])
ampns.prefix = amplitude.NAMESPACE['prefix']
ampns.update(Dict(
    upper = upper,
    lower = lower,
    ))